package org.eclipse.soc.scripting.core;

import java.io.StringReader;
import java.net.URL;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.script.ScriptException;

import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.plugin.AbstractUIPlugin;
import org.osgi.framework.BundleContext;

/**
 * ScriptBundleActivator
 * <p>
 * assumes that in the bundle root there's a script named activator.groovy 
 * which exposes a start(BundleContext) method 
 *   
 * @author ant
 * 
 */
public class ScriptBundleActivator extends AbstractUIPlugin {

	private Map<String, Object> internals = new HashMap<String, Object>();

	private ScriptExecutor scriptExecutor;

	private static ScriptBundleActivator instance;

	public ScriptBundleActivator() {
		instance = this;
	}

	public void start(BundleContext context) {
		try {
			Enumeration<?> entries = context.getBundle().findEntries("/", "activator.groovy", false);
			URL entry = null; // if the script wasn't found, then returns null
			if (entries != null && entries.hasMoreElements()) {
				entry = (URL) entries.nextElement();
			}
			
			initializeScriptingBackend(entry);
			callScriptMethod("start", new Object[] { context }, null);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void callScriptMethod(String methodName, Object[] params,
			Map<String, Object> bindings) throws ScriptException, NoSuchMethodException {
		scriptExecutor.invokeMethod(methodName, params, bindings);
	}

	private void initializeScriptingBackend(URL script) {
		scriptExecutor = new ScriptExecutor();
		try {
			scriptExecutor.evalScript(new StringReader(Util
					.getScriptContents(script)), script.getFile(), internals);
		} catch (Exception e) {
			MessageDialog.openInformation(
					Display.getCurrent().getActiveShell(), "...", "Script "
							+ " evaluation failed: " + e.getClass().getName()
							+ ": " + e.getMessage());
			throw new RuntimeException(e);
		}
	}

	public ScriptBundleActivator getInstance() {
		return instance;
	}

}
